from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
from multiprocessing.pool import ThreadPool
from multiprocessing import cpu_count
from bigfile.settings import BASE_DIR
import os
# Create your views here.

cpu_ = cpu_count()  # 获取当前cpu数量，用以启动一定线程数量的线程池子
TP = ThreadPool(cpu_)


def write_slice_file(upload, local, start_pos, end_pos, i):
    '''
    upload: 上传文件对象
    local: 本地存储文件对象
    start_pos: 切片起点
    end_pos: 切片终点
    i: 读取最终校验
    '''
    print('线程开始工作, 启动读写位置:[%s] 终止读写位置:[%s] 当前线程位置:[%s]' %
          (start_pos, end_pos, i))
    upload.seek(start_pos, 0)  # 移动远程读取文件的读写指针位置
    if i != cpu_:
        data = upload.read(end_pos - start_pos)
    else:
        data = upload.read()  # 最后一个线程工作
    local.write(data)


def transfer_large_files(upload):
    '''
    upload: 上传文件对象
    '''
    print('已开启当前cpu数量的线程池:', cpu_)
    size_ = upload.size
    print('总文件大小:', size_)
    with open(os.path.join(BASE_DIR, upload.name), 'wb') as local:
        print('本地存储路径为:', os.path.join(BASE_DIR, upload.name))
        one_pice = size_ // cpu_  # 每份读写指针大小
        print('每个线程处理的文件大小:', one_pice)
        for i in range(cpu_):
            TP.apply(func=write_slice_file, args=(
                upload, local, i * one_pice, (i+1) * one_pice, i + 1))
    print('文件写完...')


class TB_File(View):
    def get(self, request):
        return render(request, 'index.html')

    def post(self, request):
        upload = request.FILES['file']
        transfer_large_files(upload)
        return HttpResponse('OK')
